package com.cqc.actionbarcompat_listpopupmenu01;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by cui on 2017/3/19.
 */

public class PopupFragment extends ListFragment implements View.OnClickListener {

    private ArrayList<String> list = new ArrayList<String>();

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        for (int i = 0; i < 100; i++) {
            list.add("item" + i);
        }
        setListAdapter(new PopupAdapter(list));
    }


    @Override
    public void onListItemClick(ListView listView, View v, int position, long id) {
        super.onListItemClick(listView, v, position, id);
        String text = (String) listView.getItemAtPosition(position);
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        final PopupAdapter adapter = (PopupAdapter) getListAdapter();
        final String text = (String) view.getTag();

        PopupMenu menu = new PopupMenu(getActivity(), view);
        menu.getMenuInflater().inflate(R.menu.menu_popup, menu.getMenu());
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu1:
                        adapter.remove(text);
                        return true;
//                        break;
                }
                return false;
            }
        });
        menu.show();
    }

    public class PopupAdapter extends ArrayAdapter<String> {
        public PopupAdapter(ArrayList<String> list) {
            super(getActivity(), R.layout.item_list_fragment, R.id.tv1, list);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete);
            iv_delete.setTag(getItem(position));
            iv_delete.setOnClickListener(PopupFragment.this);
            return view;
        }
    }
}
